// 当前JS所在路
var js = document.scripts;
var currJsFileUrl = js[js.length - 1].src.substring(0, js[js.length - 1].src.lastIndexOf("/"));

/**
 * Jquery多文件上传控件,支持图片预览
 * @param opts
 * @constructor
 */
var FileUploadTool = function (opts){
    // 当前对象
    var _self = this;
    /**
     * 获取对象 URL
     * @param file
     * @returns {null}
     */
    _self.getObjectURL = function (file) {
        var url = null;
        if (window.createObjectURL != undefined) {
            url = window.createObjectURL(file)
        } else if (window.URL != undefined) {
            url = window.URL.createObjectURL(file)
        } else if (window.webkitURL != undefined) {
            url = window.webkitURL.createObjectURL(file)
        }
        return url;
    };

    // 模板
    var template = {
        imgsDiv: null, //容器
        fileInputName: "file_upload", //文件选择控件的统一名称
        currImgIdx: 0, //当前图片下标
        maxSize: 5 * 1024, //文件允许上传的默认最大尺寸 2MB
        isOnlyOne: null, //是否只能选择一个
        isHead: false, // 是否为头像
        fileType: 'picture', // 文件类型（picture video text）

        /**
         * 初始化
         */
        init:function(){
            // 判断是否只有一个
            template.isOnlyOne = opts.isOnlyOne ? opts.isOnlyOne : false;
            // 自定义文件file input标签的name值、自定义单文件上传判断是否为头像 begin
            template.fileInputName = opts.fileInputName ? opts.fileInputName : template.fileInputName;
            template.isHead = opts.isHead ? opts.isHead : template.isHead;
            // 自定义文件file input标签的name值、自定义单文件上传判断是否为头像 end
            if(opts.id instanceof Element){
                this.imgsDiv = opts.id;
            }if(opts.id instanceof Object && opts.id.get){
                this.imgsDiv = opts.id.get(0);
            }else{
                this.imgsDiv = document.getElementById(opts.id); //容器
            }
            this.imgsDiv.style.width = "100%";
            this.imgsDiv.style.height = "auto";

            if(!opts.maxSize){
                opts.maxSize = this.maxSize;
            }

            // 设置宽高
            if(opts.width === undefined){
                opts.width = 100;
            }
            if(opts.height === undefined){
                opts.height = 100;
            }
            template.fileType = opts.fileType ? opts.fileType : template.fileType;

            if(!opts.disableAdd || opts.disableAdd == false){
                this.imgsDiv.appendChild(this.createAddBtn(this.imgsDiv));
            }
        },

        /**
         * 创建添加文件按钮
         * @param imgsDiv
         * @returns {HTMLDivElement}
         */
        createAddBtn:function(imgsDiv){
            var itemDiv = document.createElement("div");
            itemDiv.id = "div_upload_img";
            itemDiv.style.width = opts.width + 'px';
            itemDiv.style.height = opts.height + 'px';
            itemDiv.style.margin = "5px";
            itemDiv.style.float = "left";
            itemDiv.style.backgroundColor = "#F7F7F7";
            itemDiv.style.backgroundSize = "100% 100%";

            // 判断是不是只有一个，并且是头像
            if(template.fileType == 'picture'){
                if(template.isOnlyOne && template.isHead){
                    itemDiv.style.backgroundImage = "url(" + currJsFileUrl + "/images/img_head.png)";
                }else{
                    itemDiv.style.backgroundImage = "url(" + currJsFileUrl + "/images/img_add.png)";
                }
            }
            if(template.fileType == 'video'){
                itemDiv.style.backgroundImage = "url(" + currJsFileUrl + "/images/video_add.png)";
            }
            if(template.fileType == 'text'){
                itemDiv.style.backgroundImage = "url(" + currJsFileUrl + "/images/img_add2.png)";
            }

            itemDiv.style.cursor = "pointer";
            //绑定单击事件
            itemDiv.onclick = function () {
                //创建项
                var item = template.createItem();
                imgsDiv.insertBefore(item, itemDiv);
                // 兼容Cordova
                if(typeof cordova != "undefined"){
                    if(template.fileType == 'picture'){
                        app.dialog.create({
                            title: '选择照片',
                            text: '',
                            buttons: [
                                {
                                    text: '拍照',
                                    bold: true,
                                    onClick: function (evt) {
                                        var cameraOptions= {
                                            quality : 75,
                                            destinationType : Camera.DestinationType.DATA_URL,
                                            sourceType : Camera.PictureSourceType.CAMERA,     //照相机类型
                                            //allowEdit : true,
                                            encodingType : Camera.EncodingType.JPEG,
                                            popoverOptions : CameraPopoverOptions,
                                            saveToPhotoAlbum : false
                                        };
                                        console.log("调用拍照接口");
                                        navigator.camera.getPicture(function(imageURL){
                                            var _parentElement = imgsDiv.childNodes[imgsDiv.childNodes.length - 2];
                                            _parentElement.style.display = "";
                                            var imgObj = _parentElement.childNodes[1].childNodes[0];
                                            imgObj.src = "data:image/jpeg;base64," + imageURL;
                                        }, function (e){
                                            console.log("onCameraError:"+e);
                                        },cameraOptions);
                                    }
                                },
                                {
                                    text: '相册',
                                    bold: true,
                                    onClick: function (evt) {
                                        var cameraOptions= {
                                            quality : 75,
                                            //DATA_URL=返回 base64 编码的图像，  FILE_URI=返回图像文件的位置
                                            destinationType : Camera.DestinationType.DATA_URL ,
                                            //相册类型
                                            sourceType : Camera.PictureSourceType.SAVEDPHOTOALBUM,
                                            //allowEdit : true,
                                            encodingType : Camera.EncodingType.JPEG,
                                            popoverOptions : CameraPopoverOptions,
                                            saveToPhotoAlbum : false
                                        };
                                        console.log("调用相册接口");
                                        navigator.camera.getPicture(function(imageURL){
                                            var _parentElement = imgsDiv.childNodes[imgsDiv.childNodes.length - 2];
                                            _parentElement.style.display = "";
                                            var imgObj = _parentElement.childNodes[1].childNodes[0];
                                            imgObj.src = "data:image/jpeg;base64," + imageURL;
                                        }, function (e){
                                            console.log("onCameraError:"+e);
                                        },cameraOptions);
                                    }
                                },
                                {
                                    text: '取消',
                                    bold: true,
                                    onClick: function (evt) {

                                    }
                                }
                            ],
                            verticalButtons: true
                        }).open();
                    }else if(template.fileType == 'video'){
                        app.dialog.create({
                            title: '选择视频',
                            text: '',
                            buttons: [
                                {
                                    /*text: '录像',
                                    bold: true,
                                    onClick: function (evt) {
                                        var options = {
                                            limit: 1,
                                            duration: 600 //十分钟
                                        };
                                        console.log("调用录像接口");
                                        navigator.device.capture.captureVideo(function(mediaFiles){
                                            var i, path, len;
                                            // 遍历获取录制的文件（iOS 只支持一次录制一个视频）
                                            for (i = 0, len = mediaFiles.length; i < len; i += 1) {
                                                path = mediaFiles[i].fullPath;

                                                var _parentElement = imgsDiv.childNodes[imgsDiv.childNodes.length - 2];
                                                _parentElement.style.display = "";
                                                var imgObj = _parentElement.childNodes[1].childNodes[0];
                                                imgObj.src = currJsFileUrl + "/images/play_start.png";
                                                imgObj.value = mediaFiles[i].localURL;
                                                //alert("录制成功！\n\n" + "文件名：" + mediaFiles[i].name + "\n"
                                                // + "大小：" + mediaFiles[i].size + "\n\n"
                                                // + "localURL地址：" + mediaFiles[i].localURL + "\n" + "fullPath地址：" + path);
                                            }
                                        }, function (e){
                                            if(e.code == CaptureError.CAPTURE_PERMISSION_DENIED){
                                                alert("用户拒绝执行给定捕获请求所需的权限。");
                                            }else{
                                                alert('录制失败！错误码：' + e.code);
                                            }
                                        },options);
                                    }*/
                                },
                                {
                                    text: '相册',
                                    bold: true,
                                    onClick: function (evt) {
                                        // var cameraOptions= {
                                        //     quality : 75,
                                        //     destinationType : Camera.DestinationType.DATA_URL,
                                        //     sourceType : Camera.PictureSourceType.SAVEDPHOTOALBUM,    //相册类型
                                        //     encodingType : Camera.EncodingType.JPEG,
                                        //     mediaType: Camera.MediaType.VIDEO,
                                        //     popoverOptions : CameraPopoverOptions,
                                        //     saveToPhotoAlbum : false
                                        // };
                                        // console.log("调用相册接口");
                                        // navigator.camera.getPicture(function(imageURL){
                                        //     var _parentElement = imgsDiv.childNodes[imgsDiv.childNodes.length - 2];
                                        //     _parentElement.style.display = "";
                                        //     var imgObj = _parentElement.childNodes[1].childNodes[0];
                                        // }, function (e){
                                        //     console.log("onCameraError:"+e);
                                        // },cameraOptions);
                                        item.childNodes[2].click();
                                    }
                                },
                                {
                                    text: '取消',
                                    bold: true,
                                    onClick: function (evt) {

                                    }
                                }
                            ],
                            verticalButtons: true
                        }).open();
                    }
                }else{
                    item.childNodes[2].click();
                }
            };
            return itemDiv;
        },

        /**
         * 新建项目
         * @param params
         */
        createItemNew:function(params){
            template.createItem(params.imgName, params.imgUrl, params.removeCallback, params.disableRemove, params.captureIsCamera);
        },
        /**
         * 创建项
         * @param imgName 图片名称
         * @param imgUrl 图片路径
         * @param removeCallback 图片移除成功时回调函数
         * @param boolean disableRemove 禁用删除
         * @param boolean captureIsCamera 是否调用摄像头获取
         * @param param removeCallback的参数
         * @returns {Element} 项对象
         */
        createItem: function (imgName, imgUrl, removeCallback, disableRemove, captureIsCamera,param){
            var itemDiv = document.createElement("div");
            itemDiv.style.width = opts.width + 'px';
            itemDiv.style.height = opts.height + 'px';
            itemDiv.style.margin = "5px";
            itemDiv.style.float = "left";
            itemDiv.style.position = "relative";
            itemDiv.style.display = "none";
            itemDiv.className = "ckImgItem";

            // 鼠标悬停(删除图标的显示)
            itemDiv.onmouseover = function() {
                this.childNodes[0].style.display = "";
            };
            // 鼠标移出(删除图标的隐藏)
            itemDiv.onmouseout = function() {
                this.childNodes[0].style.display = "none";
            };

            // 删除图标的使用
            if(!disableRemove || disableRemove == false){
                var divRemove = template.findRemoveDiv(imgName,removeCallback,param);
                // 添加删除按钮
                itemDiv.appendChild(divRemove);
            }

            // 创建图片div
            var divimg = document.createElement("div");
            var img = document.createElement("img");
            img.id = "ImgPr" + template.currImgIdx;
            img.name = "img_upload";
            img.style.width = opts.width + 'px';
            img.style.height = opts.height + 'px';
            divimg.appendChild(img);
            itemDiv.appendChild(divimg);

            var inputimg = document.createElement("input");
            inputimg.type = "file";
            inputimg.id = "up" + template.currImgIdx;
            inputimg.name = template.fileInputName;
            if(template.fileType == 'picture'){
                inputimg.accept = "image/*";
            }
            if(template.fileType == 'video'){
                inputimg.accept = "video/*";
            }

            inputimg.style.display = "none";

            if(captureIsCamera){
                inputimg.accept = "image/*;capture=camera";
            }

            if(!imgUrl) {
                // 文件更改事件
                if(template.fileType == 'video'){
                    inputimg.onchange = function (evt) {
                        var tempFileSize = template.getFileSize(this);

                        if(tempFileSize == 0 || tempFileSize > opts.maxSize){
                            $(this).remove();
                            if(typeof layer != "undefined" && layer.alert){
                                layer.alert("视频太大，视频最大不能超过 " + (opts.maxSize / 1024) + "MB！", {icon: 2});
                            }else{
                                alert("视频太大，图片最大不能超过 " + (opts.maxSize / 1024) + "MB！");
                            }
                            return;
                        }

                        var _parentElement = this.parentNode;
                        _parentElement.style.display = "";

                        var imgObj = this.parentNode.childNodes[1].childNodes[0];

                        if (!$.support.style) { /* 判断浏览器是否为IE */
                            try {
                                imgObj.src = _self.getObjectURL(this.files[0]);
                                imgObj.src = currJsFileUrl + "/images/play_start.png";
                                imgObj.src = template.getVideoBase64(imgObj,_self.getObjectURL(this.files[0]));
                                if(!disableRemove || disableRemove == false){
                                    var divRemove = template.findRemoveDiv(imgName,removeCallback,param);
                                    itemDiv.appendChild(divRemove);
                                }
                            } catch (e) {
                                var src = "";
                                var obj = imgObj;
                                var div = obj.parent("div")[0];
                                _self.select();
                                if (top != self) {
                                    window.parent.document.body.focus();
                                } else {
                                    _self.blur();
                                }
                                src = document.selection.createRange().text;
                                document.selection.empty();
                                obj.hide();
                                obj.parent("div").css({
                                    'filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)',
                                    'width': opts.width + 'px',
                                    'height': opts.height + 'px'
                                });
                                div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src;
                            }
                        } else {
                            imgObj.src = _self.getObjectURL(this.files[0]);
                            imgObj.src = currJsFileUrl + "/images/play_start.png";
                            template.getVideoBase64(imgObj,_self.getObjectURL(this.files[0]));
                            if(!disableRemove || disableRemove == false){
                                var divRemove = template.findRemoveDiv(imgName,removeCallback,param);
                                itemDiv.appendChild(divRemove);
                            }
                        }

                        //如果指定只能选择一个文件，则在选择完成后移除添加项
                        if(template.isOnlyOne){
                            var node = _parentElement.parentNode.children[_parentElement.parentNode.children.length - 1];
                            _parentElement.parentNode.removeChild(node);
                        }
                        template.deleteNull();
                    };
                }else {
                    inputimg.onchange = function (evt) {
                        var tempFileSize = template.getFileSize(this);

                        if(tempFileSize == 0 || tempFileSize > opts.maxSize){
                            $(this).remove();
                            if(typeof layer != "undefined" && layer.alert){
                                layer.alert("图片太大，图片最大不能超过 " + (opts.maxSize / 1024) + "MB！", {icon: 2});
                            }else{
                                alert("图片太大，图片最大不能超过 " + (opts.maxSize / 1024) + "MB！");
                            }
                            return;
                        }

                        var _parentElement = this.parentNode;
                        _parentElement.style.display = "";

                        var imgObj = this.parentNode.childNodes[1].childNodes[0];

                        if (!$.support.style) { /* 判断浏览器是否为IE */
                            try {
                                imgObj.src = _self.getObjectURL(this.files[0]);
                            } catch (e) {
                                var src = "";
                                var obj = imgObj;
                                var div = obj.parent("div")[0];
                                _self.select();
                                if (top != self) {
                                    window.parent.document.body.focus();
                                } else {
                                    _self.blur();
                                }
                                src = document.selection.createRange().text;
                                document.selection.empty();
                                obj.hide();
                                obj.parent("div").css({
                                    'filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)',
                                    'width': opts.width + 'px',
                                    'height': opts.height + 'px'
                                });
                                div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src
                            }
                        } else {
                            imgObj.src = _self.getObjectURL(this.files[0]);
                        }

                        //如果指定只能选择一个文件，则在选择完成后移除添加项
                        if(template.isOnlyOne){
                            var node = _parentElement.parentNode.children[_parentElement.parentNode.children.length - 1];
                            _parentElement.parentNode.removeChild(node);
                        }
                        template.deleteNull();
                    };
                }
                itemDiv.appendChild(inputimg);
            }else{
                itemDiv.style.display = "";

                if(template.fileType == 'video'){
                    if (!$.support.style) { /* 判断浏览器是否为IE */
                        try {
                            img.src = imgUrl;
                            img.src = currJsFileUrl + "/images/play_start.png";
                            template.getVideoBase64(img,imgUrl);
                            if(!disableRemove || disableRemove == false){
                                var divRemove = template.findRemoveDiv(imgName,removeCallback,param);
                                itemDiv.appendChild(divRemove);
                            }

                        } catch (e) {
                            var src = "";
                            var obj = img;
                            var div = obj.parent("div")[0];
                            _self.select();
                            if (top != self) {
                                window.parent.document.body.focus();
                            } else {
                                _self.blur();
                            }
                            src = document.selection.createRange().text;
                            document.selection.empty();
                            obj.hide();
                            obj.parent("div").css({
                                'filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)',
                                'width': opts.width + 'px',
                                'height': opts.height + 'px'
                            });
                            div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src;
                        }
                    } else {
                        img.src = imgUrl;
                        img.src = currJsFileUrl + "/images/play_start.png";
                        template.getVideoBase64(img,imgUrl);
                        if(!disableRemove || disableRemove == false){
                            if(divRemove){
                                divRemove.remove();
                            };
                            var divRemove = document.createElement("div");
                            divRemove.name = imgName;
                            divRemove.className = "div_remove";
                            divRemove.style.width = "30%";
                            divRemove.style.height = "30%";
                            divRemove.style.float = "left";
                            divRemove.style.position = "absolute";
                            divRemove.style.cursor = "pointer";
                            divRemove.style.top = "0px";
                            divRemove.style.right = "0px";
                            divRemove.style.cursor = "pointer";
                            divRemove.style.backgroundImage = "url('" + currJsFileUrl + "/images/remove.png')";
                            divRemove.style.backgroundSize = "100%";
                            divRemove.style.backgroundRepeat = "no-repeat";
                            //divRemove.style.display = "none";
                            divRemove.onclick = function(){
                                var _parentElement = this.parentNode.parentNode;
                                if(_parentElement){
                                    _parentElement.removeChild(this.parentNode);
                                }

                                if(removeCallback){
                                    removeCallback(param);
                                }
                            };
                            itemDiv.appendChild(divRemove);
                        }
                    }
                }else {
                    if (!$.support.style) { /* 判断浏览器是否为IE */
                        try {
                            img.src = imgUrl;
                        } catch (e) {
                            var src = "";
                            var obj = img;
                            var div = obj.parent("div")[0];
                            _self.select();
                            if (top != self) {
                                window.parent.document.body.focus()
                            } else {
                                _self.blur()
                            }
                            src = document.selection.createRange().text;
                            document.selection.empty();
                            obj.hide();
                            obj.parent("div").css({
                                'filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)',
                                'width': opts.width + 'px',
                                'height': opts.height + 'px'
                            });
                            div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src;
                        }
                    } else {
                        img.src = imgUrl;
                    }
                }

                itemDiv.appendChild(inputimg);
                // 删除图标绑定鼠标事件 begin
                if (!template.isOnlyOne || template.isHead || !!disableRemove) {
                    itemDiv.onmouseover = undefined;
                    itemDiv.onmouseout = undefined;
                } else {
                    itemDiv.childNodes[0].style.display = "none";
                }
                // 删除图标绑定鼠标事件 end
                var lastChild = template.imgsDiv.lastChild;
                template.imgsDiv.insertBefore(itemDiv, lastChild);
                // 当前图片个数动态变更 begin
                template.currImgIdx++;
                // 当前图片个数动态变更 end
            }

            // 优化判断，当前限制仅选择一张图片时，创建完成后，移除添加项 begin
            if (template.isOnlyOne && template.currImgIdx >= 1) {
                itemDiv.parentNode.removeChild(itemDiv.parentNode.children[itemDiv.parentNode.children.length - 1])
            }
            // 优化判断，当前限制仅选择一张图片时，创建完成后，移除添加项 end

            return itemDiv;
        },
        /**
         * 获取文件大小
         * @param fileObj 文件控件对象
         * @returns {number} 文件大小
         */
        getFileSize: function (fileObj) {
            var fileSize = 0;
            try {
                // IE浏览器
                if ($.support.msie) {
                    //before making an object of ActiveXObject,
                    //please make sure ActiveX is enabled in your IE browser
                    var objFSO = new ActiveXObject("Scripting.FileSystemObject");
                    var filePath = fileObj.value;
                    var objFile = objFSO.getFile(filePath);
                    fileSize = objFile.size; // size in b
                    fileSize = fileSize / 1024; // size in kb
                } else { // for FF, Safari, Opeara and Others
                    fileSize = fileObj.files[0].size; //size in b
                    fileSize = fileSize / 1024; //size in kb
                }
            } catch (e) {
                console.log("获取文件大小时发生异常：",e);
            }
            return fileSize;
        },
        /**
         * 生成base64格式图片作为  封面
         */
        getVideoBase64: function (img,url) {
            let dataURL = '';
            let video = document.createElement("video");
            video.setAttribute('crossOrigin', 'anonymous');//处理跨域
            video.setAttribute('src', url);
            video.setAttribute('width', 400);
            video.setAttribute('height', 240);
            video.setAttribute('autoplay',"autoplay");
            video.addEventListener('loadeddata', function () {
                setTimeout(function () {
                    let canvas = document.createElement("canvas"),
                        width = video.width, //canvas的尺寸和图片一样
                        height = video.height;
                    canvas.width = width;
                    canvas.height = height;
                    canvas.getContext("2d").drawImage(video, 0, 0, width, height); //绘制canvas
                    dataURL = canvas.toDataURL('image/jpeg'); //转换为base64
                    img.src=dataURL;
                    $(img).css("position","absolute");
                    $(img).parent().append("<img class='playButton' data='"+url+"' src='"+currJsFileUrl+"/images/play_start3.png"
                        +"'  style='position:relative;height: 40px;width:40px;left:calc(("
                        + opts.width +"px - 40px)/2);top:calc((" + opts.height + "px - 40px)/2);border:0px'/>");
                    $(".playButton").off("click");
                    $(".playButton").on("click", function(){
                        var url_=$(this).attr('data');
                        layer.open({
                            type:2,
                            title:false,
                            area:['1200px','800px'],
                            shade:0.8,
                            closeBtn:1,
                            shadeClose:true,
                            content:url_
                        })
                    })
                }, 500);
            });
            if(dataURL){
                return dataURL;
            }

        },

        /**
         * 判断是否已经添加文件
         */
        isExist: function () {
            var imgs = $("input[name='" + template.fileInputName + "']")
            var result = false;
            for(var i = 0;i < imgs.length;i++){
                if(imgs[i].files.length > 0 && imgs[i].files[0].name != ''){
                    result = true;
                }
            }
            console.log(result);
            return result;
        },

        /**
         * 相册查看，需要layer支持
         * @param id
         */
        photos: function (id){
            layer.photos({
                photos:'#' + (id == undefined ? opts.id : id),
                title: false,
                closeBtn:2,
                shadeClose:true,
                shift:5
            });
        },

        /**
         * 创建删除div
         * @param imgName
         * @param removeCallback
         * @param param
         * @returns {HTMLDivElement}
         */
        findRemoveDiv: function (imgName,removeCallback,param){
            var divRemove = document.createElement("div");
            divRemove.name = imgName;
            divRemove.className = "div_remove";
            divRemove.style.width = "20%";
            divRemove.style.height = "20%";
            divRemove.style.maxWidth = "128px";
            divRemove.style.maxHeight = "128px";
            divRemove.style.float = "left";
            divRemove.style.position = "absolute";
            divRemove.style.cursor = "pointer";
            divRemove.style.top = "0px";
            divRemove.style.right = "0px";
            divRemove.style.cursor = "pointer";
            divRemove.style.backgroundImage = "url('" + currJsFileUrl + "/images/remove.png')";
            divRemove.style.backgroundSize = "100%";
            divRemove.style.backgroundRepeat = "no-repeat";

            divRemove.onclick = function(){
                var _parentElement = this.parentNode.parentNode;
                if(_parentElement){
                    _parentElement.removeChild(this.parentNode);
                }
                if(_parentElement.childNodes.length == 0){
                    template.imgsDiv.appendChild(template.createAddBtn(template.imgsDiv));
                }
                // 当前图片个数动态变更
                template.currImgIdx--;
                // 删除回调函数
                if(removeCallback){
                    removeCallback(param);
                }
            }
            return divRemove;
        },

        /**
         * 删除空的input
         */
        deleteNull: function (){
            var imgs = $("input[name='" + template.fileInputName + "']")
            for(var i = 0;i < imgs.length;i++){
                if(imgs[i].files.length == 0 || imgs[i].files[0].name == ''){
                    $(imgs[i]).remove();
                }
            }
        }
    };



    // 返回创建的对象
    return (function init(){
        template.init();
        return template;
    })();
};